package com.daiyilu.com.office4all.pdf;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.*;

import java.io.*;

public class PdfWaterMask {

    public static void maskWords(String filePath,String words, FileOutputStream outputStream) {
        try {
            // 添加水印的时候,就已经在outputStream写入了
            final InputStream inputStream = new FileInputStream(filePath);
            PdfReader reader = new PdfReader(inputStream);
            PdfStamper stamper = new PdfStamper(reader, outputStream);
            int total = reader.getNumberOfPages() + 1;
            PdfContentByte content;
            //todo 替换字体文件
            BaseFont base = BaseFont.createFont("simfang.ttf", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
            PdfGState gs = new PdfGState();
            for (int i = 1; i < total; i++) {
                content = stamper.getOverContent(i);// 在内容上方加水印 stamper.getUnderContent(i);//在内容下方加水印
                gs.setFillOpacity(0.5f);
                content.setGState(gs);
                content.beginText();
                content.setTextMatrix(0, 0);
                //将文字显示在pdf页面中
                //设置文字颜色
                content.setColorFill(BaseColor.RED);
                //设置文字大小
                content.setFontAndSize(base, 50);
                content.showTextAligned(Element.ALIGN_CENTER, words, 300, 400, 45);
                content.endText();
            }
            stamper.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            maskWords("D:\\demo.pdf","宸帆电子商务有限公司",new FileOutputStream( "watermask.pdf"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }


}
